// src/utils/request.js
import axios from 'axios'
import { TOKEN_KEY } from './auth'
import router from '@/router'
import { useUserStore } from '@/stores/user'

const service = axios.create({
  baseURL: '/api/v1'
})

// 请求拦截器
service.interceptors.request.use(config => {
  const token = localStorage.getItem(TOKEN_KEY)
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

// 响应拦截器：token 失效自动跳转登录
service.interceptors.response.use(
  res => res,
  error => {
    const store = useUserStore()
    if (error.response?.status === 401) {
      store.logout()
      router.push('/login')
    }
    return Promise.reject(error)
  }
)

export default service
